﻿using FictionsDownload.DAL;
using FictionsDownload.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace FictionsDownload.BLL
{
    public class BaseBLL:EfBLL
    {
        /// <summary>
        /// 成功失败等反馈信息
        /// </summary>
        public string Message { get; set; }
        public BaseBLL()
        {
            dal = db_Fictions.Create();
        }
        public BaseBLL(IDAL repository)
        {
            dal = repository;
        }
        public void SetDAL(IDAL repository)
        {
            dal = repository;
        }
        /// <summary>
        /// 获取指定条件中第一个实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public T Get<T>(Expression<Func<T, bool>> conditions) where T : class
        {
            return All<T>().FirstOrDefault(conditions);
        }

        public IQueryable<T> Find<T>(Expression<Func<T, bool>> conditions = null) where T : class
        {
            if (conditions != null)
            {
                return Set<T>().Where(conditions);
            }
            else
            {
                return Set<T>();
            }
        }

        public IQueryable<T> Find<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex, out int totalCount) where T : class
        {
            var queryList = Find(conditions);
            totalCount = queryList.Count();
            return queryList.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }

        public List<T> GetList<T>(Expression<Func<T, bool>> conditions = null) where T : class
        {
            if(conditions == null)
            {
                return All<T>().ToList();
            }
            else
            {
                return All<T>().Where(conditions).ToList();
            }
        }

        public List<T> GetList<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex, out int totalCount) where T : class
        {
            var queryList = All<T>().Where(conditions);
            totalCount = queryList.Count();
            return queryList.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

    }
}
